package com.example.pc.videodemo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.telecom.TelecomManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.SimpleFormatter;

import retrofit2.Response;
import retrofit2.http.Url;

import static android.content.Context.TELECOM_SERVICE;

public class Util
{
    public static SharedPreferences sharedPreferences;

    private static void getSp(Context context)
    {
        if (sharedPreferences == null)
        {
            sharedPreferences = context.getSharedPreferences("ipAddress", Context.MODE_PRIVATE);
        }
    }

    public static void saveAddress(Context context, String s)
    {
        getSp(context);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString("ipAddress", s);
        edit.apply();
    }

    /**
     * Android M 以上检查是否是系统默认电话应用
     */
    public static boolean isDefaultPhoneCallApp(Context context)
    {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            TelecomManager manger = (TelecomManager) context.getSystemService(TELECOM_SERVICE);
            if (manger != null)
            {
                String name = manger.getDefaultDialerPackage();
                return name.equals(context.getPackageName());
            }
        }
        return false;
    }

    public static String getIp(Context context)
    {
        getSp(context);
//        return sharedPreferences.getString("ipAddress", "222.187.232.121");
        return sharedPreferences.getString("ipAddress", "153.36.242.22");
//        return sharedPreferences.getString("ipAddress", ""); 
    }

    /**
     * 获取当前的网络状态 ：没有网络-0：WIFI网络1：4G网络-4：3G网络-3：2G网络-2
     * 自定义
     *
     * @param context
     * @return
     */
    public static int getAPNType(Context context)
    {
        //结果返回值
        int netType = 0;
        //获取手机所有连接管理对象
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //获取NetworkInfo对象
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        //NetworkInfo对象为空 则代表没有网络
        if (networkInfo == null)
        {
            return netType;
        }
        //否则 NetworkInfo对象不为空 则获取该networkInfo的类型
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_WIFI)
        {
            //WIFI
            netType = 1;
        }
        else if (nType == ConnectivityManager.TYPE_MOBILE)
        {
            int nSubType = networkInfo.getSubtype();
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            //3G   联通的3G为UMTS或HSDPA 电信的3G为EVDO
            if (nSubType == TelephonyManager.NETWORK_TYPE_LTE && !telephonyManager.isNetworkRoaming())
            {
                netType = 4;
            }
            else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS || nSubType == TelephonyManager.NETWORK_TYPE_HSDPA || nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0 && !telephonyManager.isNetworkRoaming())
            {
                netType = 3;
                //2G 移动和联通的2G为GPRS或EGDE，电信的2G为CDMA
            }
            else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS || nSubType == TelephonyManager.NETWORK_TYPE_EDGE || nSubType == TelephonyManager.NETWORK_TYPE_CDMA && !telephonyManager.isNetworkRoaming())
            {
                netType = 2;
            }
            else
            {
                netType = 2;
            }
        }
        return netType;
    }

    boolean isMyLauncherDefault(Context context)
    {

        final IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);

        filter.addCategory(Intent.ACTION_NEW_OUTGOING_CALL);
        filter.addCategory(Intent.ACTION_CALL);
        filter.addCategory(Intent.ACTION_DIAL);

        List filters = new ArrayList();

        filters.add(filter);

        final String myPackageName = context.getPackageName();

        List<ComponentName> activities = new ArrayList<>();

        final PackageManager packageManager = (PackageManager) context.getPackageManager();

// You can use name of your package here as third argument

        packageManager.getPreferredActivities(filters, activities, null);

        for (ComponentName activity : activities)
        {

            if (myPackageName.equals(activity.getPackageName()))
            {

                return true;

            }

        }

        return false;

    }


    public static File upload(Context context, String s, String toString)
    {
        String CACHE_FILE_PATH = context.getExternalCacheDir().getPath();
        DateFormat simpleFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "_" + toString + "_" + s + "_" + simpleFormatter.format(new Date()) + ".zip";
        File extDir = new File(CACHE_FILE_PATH);

        File outFile = new File(extDir, fileName);//源文件或者目录

        try
        {
            outFile.createNewFile();
            outFile = ZipUtil.zip(CACHE_FILE_PATH + "/log", outFile);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

//        if (outFile == null)
//        {
        return outFile;
//        }

//        uploadFile(MyContext.getIp() + "renren-fast/sys/oss/upload" , outFile.getPath(), fileName);
    }

    public static void uploadFile(String urlstr, String uploadFile, String newName)
    {
        StringBuilder log = new StringBuilder();
        Map<String, Object> header = new HashMap<String, Object>();
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";//边界标识
        int TIME_OUT = 30 * 1000;   //超时时间
        HttpURLConnection httpConn = null;
        DataOutputStream ds = null;
        InputStream is = null;
        try
        {
            URL url = new URL(urlstr);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setReadTimeout(TIME_OUT);
            httpConn.setConnectTimeout(TIME_OUT);
            /* 允许Input、Output，不使用Cache */
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            httpConn.setUseCaches(false);

            // 设置http连接属性
            httpConn.setRequestMethod("POST");//请求方式
            httpConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");


//            con.setRequestProperty("connection", "keep-alive");
//            con.setRequestProperty("Charset", "UTF-8");//设置编码
            httpConn.setRequestProperty("Content-Type",//multipart/form-data能上传文件的编码格式
                    "multipart/form-data;boundary=" + "--------------------------814501365660530225676842");

            ds = new DataOutputStream(httpConn.getOutputStream());
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; " + "name=\"file\";filename=\"" + newName + "\"" + end);
            ds.writeBytes(end);

            // 取得文件的FileInputStream
            FileInputStream fStream = new FileInputStream(uploadFile);
            /* 设置每次写入1024bytes */
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int length = -1;
            /* 从文件读取数据至缓冲区 */
            while ((length = fStream.read(buffer)) != -1)
            {
                /* 将资料写入DataOutputStream中 */
                ds.write(buffer, 0, length);
            }
            ds.writeBytes(end);
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);//结束

            fStream.close();
            ds.flush();
            /* 取得Response内容 */
            int resultCode = httpConn.getResponseCode();
            String resData = dealResponseResult(httpConn.getInputStream());
            log.append(String.format("[返回时间]%s\n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date())));
            log.append(String.format("[返回码]%s\n", resultCode));
            log.append(String.format("[结果]%s\n", resData));
            Log.i("WebClient", log.toString());
            closeIO(ds, is, httpConn);
            File outFile = new File(uploadFile);//源文件或者目录
            outFile.delete();

          /*  File logList = new File(String.valueOf((MyApplication.Companion.getAppContext()).getExternalCacheDir()));//源文件或者目录
            if (logList.exists()&&logList.isDirectory())
            {
                File[] files = logList.listFiles();
                for (File file : files)
                {
                    if (file.isFile())
                    {
                    file.delete();
                    }

                }
            }*/
        }
        catch (Exception e)
        {
            closeIO(ds, is, httpConn);
            File extDir = Environment.getExternalStorageDirectory();
            File outFile = new File(extDir, newName);//源文件或者目录
            outFile.delete();
        }
        finally
        {

        }
    }

    private static void closeIO(DataOutputStream ds, InputStream is, HttpURLConnection httpConn)
    {
        /* 关闭DataOutputStream */
        if (ds != null)
        {
            try
            {
                ds.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        if (is != null)
        {
            try
            {
                is.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        if (httpConn != null)
        {
            httpConn.disconnect();
        }
    }

    /**
     * 处理返回的的数据
     *
     * @param inputStream
     * @return
     */
    private static String dealResponseResult(InputStream inputStream)
    {
        StringBuffer sb = new StringBuffer();
        String readLine = new String();
        try
        {

            BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((readLine = responseReader.readLine()) != null)
            {
                sb.append(readLine).append("\n");
            }
            responseReader.close();

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return sb.toString();
    }

public static interface UpdateListener{
        void onNew(String url);
}
    public static void getUpdate(int kind,UpdateListener updateListener)
    {
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    URL url = new URL("https://aliyunsudo.oss-cn-shenzhen.aliyuncs.com/json/update.json");
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    int responseCode = urlConnection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK)
                    {
                        InputStream inputStream = urlConnection.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
                        StringBuilder strber = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null)
                        {
                            strber.append(line + "\n");
                        }

                        JSONObject jsonObject = new JSONObject(strber.toString());
                        String versionCode = jsonObject.getString("version");
                        int version = BuildConfig.VERSION_CODE;
                        if (version<Integer.parseInt(versionCode)){
                            Log.i("getUpdate", "有新版本"+versionCode);
                            String urlString ;
                            switch (kind){
                                case 0:
                                    urlString = jsonObject.getString("con");
                                    break;
                                case 1:
                                    urlString = jsonObject.getString("sim");
                                    break;
                                default:
                                    urlString = jsonObject.getString("voi");
                                    break;
                            }
                            updateListener.onNew(urlString);
                        }else {
                            Log.i("getUpdate", "没有新版本"+versionCode);

                        }
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * Returns the number of phones available.
     * Returns 1 for Single standby mode (Single SIM functionality)
     * Returns 2 for Dual standby mode.(Dual SIM functionality)
     */
    public static int getSimCardCount(Context context) {
        TelephonyManager mTelephonyManager = (TelephonyManager)         context.getSystemService(Context.TELEPHONY_SERVICE);
        Class cls = mTelephonyManager.getClass();
        try {
            Method mMethod = cls.getMethod("getSimCount");
            mMethod.setAccessible(true);
            return (int) mMethod.invoke(mTelephonyManager);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
